<?php

namespace App\Services;

use App\Interfaces\UserInterface;
use Illuminate\Support\Facades\DB;

class UserService implements UserInterface
{
    public function getUserPage(string $tenantId, array $params = [], int $page = 1, int $limit = 10): array
    {
        $where = array(
            ['tenantId',$tenantId],
            ['deleted',0],
            ['username','like','%'.$params['username'].'%'],
            ['nickname','like','%'.$params['nickname'].'%'],
            ['sex','like','%'.$params['sex'].'%']
        );
        $sort = empty($params['sort'])?'userId':$params['sort'];
        $order = empty($params['order'])?'ASC':$params['order'];
        $res = DB::table('users')
            ->where($where)
            ->offset($page - 1)
            ->orderBy($sort,$order)
            ->paginate($limit);
        $data['count'] = $res->total();
        $data['list'] = $res->items();
        return $data;
    }

    public function updateUser(array $data): int
    {
        $res = DB::table('users')->where('userId',$data['userId'])->update($data);
        return $res;
    }

    public function existence(array $data): bool
    {
        $where = array(
            ['username',$data['username']],
            ['deleted',0],
            ['tenantId',$data['tenantId']]
        );
        if (!empty($data['id'])){
            $where[] = ['userId', '!=', $data['id']];
        }
        $res = DB::table('users')->where($where)->exists();
        return $res;
    }

    public function createUser(array $data): int
    {
        $res = DB::table('users')->insertGetId($data);
        return $res;
    }

    public function updateBatch(array $ids, array $data): int
    {
        $res = DB::table('users')->whereIn('userId',$ids)->update($data);
        return $res;
    }
}

